package com.opencv.controller;

import com.opencv.utils.FileUploadUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.IOUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author qz.wu
 * @Classname ImageController
 * @Description TODO
 * @Date 2021/7/1 13:30
 */
@RestController
@RequestMapping("/images")
public class ImageController {

    @GetMapping("/watermark")
    public String watermark() {
        try {
            String sourceImgPath = "E:\\workCode\\opencv-demo\\src\\main\\resources\\images\\learn.png";
            String tarImgPath = "E:\\workCode\\opencv-demo\\src\\main\\resources\\images\\watermark.png";
            String waterMarkContent = "硅基认证专用";
            String fileExt = "png";
            String lasterPicture = "E:\\workCode\\opencv-demo\\src\\main\\resources\\images\\watermark_new.png";
            addWatermark(sourceImgPath, tarImgPath, waterMarkContent, fileExt, lasterPicture);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "成功";
    }

    @PostMapping("/avatar/upload")
    public String uploadImg(@RequestParam(value = "file", required = true) MultipartFile file) { // 水印文字大小
        int fontSize = 18;
        // 水印之间的间隔
        int xMove = 50;
        // 水印之间的间隔
        int yMove = 50;
        //水印颜色: 暗灰
        Color markContentColor = new Color(105, 105, 105);
        //设置水印文字的旋转角度
        Integer degree = -45;
        // 设置水印透明度 默认为1.0  值越小颜色越浅
        float alpha = 0.5f;
        OutputStream outImgStream = null;
        OutputStream outImgStream2 = null;
        String fileExt = FileUploadUtils.getExtension(file);
        String lasterPicture = "E:\\workCode\\opencv-demo\\src\\main\\resources\\images\\watermark_upload.png";
        String tarImgPath = "E:\\workCode\\opencv-demo\\src\\main\\resources\\images\\watermark_tar.png";
        String waterMarkContent = "硅基医生认证专用";
        try {
            BufferedImage srcImg = ImageIO.read(file.getInputStream());
            //获取图片的宽
            int srcImgWidth = srcImg.getWidth(null);
            //获取图片的高
            int srcImgHeight = srcImg.getHeight(null);
            //水印字体，大小
            Font font = new Font("宋体", Font.BOLD, fontSize);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = bufImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH),
                    0, 0, null);
            // 设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2);
            }
            //设置水印颜色
            g.setColor(markContentColor);
            //设置字体
            g.setFont(font);
            // 设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int x = -srcImgWidth / 2;
            int y = -srcImgHeight / 2;
            // 字体长度
            int markWidth = fontSize * getTextLength(waterMarkContent);
            // 字体高度
            int markHeight = fontSize;

            // 循环添加水印
            while (x < srcImgWidth * 1.5) {
                y = -srcImgHeight / 2;
                while (y < srcImgHeight * 1.5) {
                    g.drawString(waterMarkContent, x, y);

                    y += markHeight + yMove;
                }
                x += markWidth + xMove;
            }
            // 释放资源
            g.dispose();
            // 输出图片
            outImgStream = new FileOutputStream(tarImgPath);
            outImgStream2 = new FileOutputStream(lasterPicture);
            ImageIO.write(bufImg, fileExt, outImgStream);
            ImageIO.write(bufImg, fileExt, outImgStream2);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (outImgStream != null) {
                    outImgStream.flush();
                    outImgStream.close();
                }
                if (outImgStream2 != null) {
                    outImgStream2.flush();
                    outImgStream2.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "上传成功";
    }

    /**
     * @param sourceImgPath    源图片路径
     * @param tarImgPath       保存的图片路径
     * @param waterMarkContent 水印内容
     * @param fileExt          图片格式
     * @param lasterPicture    最新一期图片存放位置
     * @return void
     * @description
     */
    public void addWatermark(String sourceImgPath, String tarImgPath, String waterMarkContent, String fileExt, String lasterPicture) {
        // 水印文字大小
        int FONT_SIZE = 18;
        // 水印之间的间隔
        int XMOVE = 50;
        // 水印之间的间隔
        int YMOVE = 50;
//		Color markContentColor = Color.red;//水印颜色
        //水印颜色
        Color markContentColor = new Color(105, 105, 105);
        //设置水印文字的旋转角度
        Integer degree = -45;
        //设置水印透明度 默认为1.0  值越小颜色越浅
        float alpha = 0.5f;
        OutputStream outImgStream = null;
        OutputStream outImgStream2 = null;
        try {
            //得到文件
            File srcImgFile = new File(sourceImgPath);
            //文件转化为图片
            Image srcImg = ImageIO.read(srcImgFile);
            //获取图片的宽
            int srcImgWidth = srcImg.getWidth(null);
            //获取图片的高
            int srcImgHeight = srcImg.getHeight(null);
            if (srcImgWidth < srcImgHeight) {
                FONT_SIZE = 18;
                XMOVE = 130;
                YMOVE = 130;
            }
            //水印字体，大小
            Font font = new Font("宋体", Font.BOLD, FONT_SIZE);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = bufImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH),
                    0, 0, null);
            // 设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2);
            }
            //设置水印颜色
            g.setColor(markContentColor);
            //设置字体
            g.setFont(font);
            // 设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int x = -srcImgWidth / 2;
            int y = -srcImgHeight / 2;
            // 字体长度
            int markWidth = FONT_SIZE * getTextLength(waterMarkContent);
            // 字体高度
            int markHeight = FONT_SIZE;

            // 循环添加水印
            while (x < srcImgWidth * 1.5) {
                y = -srcImgHeight / 2;
                while (y < srcImgHeight * 1.5) {
                    g.drawString(waterMarkContent, x, y);

                    y += markHeight + YMOVE;
                }
                x += markWidth + XMOVE;
            }
            // 释放资源
            g.dispose();
            // 输出图片
            outImgStream = new FileOutputStream(tarImgPath);
            outImgStream2 = new FileOutputStream(lasterPicture);
            ImageIO.write(bufImg, fileExt, outImgStream);
            ImageIO.write(bufImg, fileExt, outImgStream2);
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        } finally {
            try {
                if (outImgStream != null) {
                    outImgStream.flush();
                    outImgStream.close();
                }
                if (outImgStream2 != null) {
                    outImgStream2.flush();
                    outImgStream2.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                e.getMessage();
            }
        }
    }

    /**
     * 获取文本长度。汉字为1:1，英文和数字为2:1
     */
    private int getTextLength(String text) {
        int length = text.length();
        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }
}
